<?php
namespace App\Api\Controllers\Basequery;

use App\Api\Controllers\BaseController;
use App\Models\MerchantStore;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Image;
use TencentYoutuyun\Conf;
use TencentYoutuyun\YouTu;

//use AlibabaCloud\SDK\Ocrapi\V20210707\Ocrapi;
//use Darabonba\OpenApi\Models\Config;
//use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeAdvancedRequest;

class UploadController extends BaseController{

    public function upload(Request $request, $file_key = 'attach_name', $type = 'img'){
        try {
            $token = $request->get('token');
            $merchant = $this->parseToken($token);
            if ($merchant==false) {
                return response()->json([
                    'status' => 2,
                    'message' => '账户过期请重新登录！'
                ]);
            }
            $img_type = $request->get('img_type', '');
            $file_key = trim($request->get('attach_name')) ? trim($request->get('attach_name')) : $file_key;
            $type = $request->get('type', 'img');

            $up = Input::hasFile($file_key); //检测是否有上传文件  返回布尔值
            if (!$up) {
                return response()->json([
                    'status' => 2,
                    'message' => '未识别到文件！'
                ]);
            }

            $public_dir = public_path();
            $disk_dir = $public_dir;
            $web_dir = 'upload';
            if (!is_dir($public_dir . '/' . $web_dir)) {
                return response()->json([
                    'status' => 2,
                    'message' => '服务器初始目录未设置！'
                ]);
            }

            // 上传图片
            if ($type == 'img') {
                $web_dir .= '/images';
                $disk_dir = $public_dir . '/' . $web_dir;
            }

            // 上传商品图片
            if ($type == 'shop') {
                $web_dir .= '/images/shop/' . $merchant->id;
                $disk_dir = $public_dir . '/' . $web_dir;
            }

            // 上传附件
            if ($type == 'file') {
                $web_dir .= '/attach/' . date('Y/m/d');
                $disk_dir = $public_dir . '/' . $web_dir;
            }

            $ok = true;
            !is_dir($disk_dir) && $ok = mkdir($disk_dir, 0777, true);
            if ($ok === false) {
                return response()->json([
                    'status' => 2,
                    'message' => '服务器权限不够'
                ]);

            }

            $file = Input::file($file_key);
            $extension = $file->getClientOriginalExtension(); //上传文件的后缀   png

            if(!in_array(strtolower($extension),['jpg','png','gif','jpeg','pem','mp4','key'])){
                return json_encode([
                    'status' => 2,
                    'message' => '格式不支持',
                ]);
            }

            $new_name = date('His') . '_' . mt_rand(100, 999) . '.' . $extension;

            $web_pic_url = url($web_dir . '/' . $new_name);

            $return = $file->move($disk_dir, $new_name);

            if (file_exists($disk_dir . '/' . $new_name)) {
                //上传到阿里云oss
                if (env('ALIOSS_AccessKeyId')) {
                    //阿里云oss
                    $AccessKeyId = env('ALIOSS_AccessKeyId');
                    $AccessKeySecret = env('ALIOSS_AccessKeySecret');
                    $endpoint = env('ALIOSS_endpoint');
                    $bucket = env('ALIOSS_bucket');
                    $object = $new_name;
                    try {
                        $content = file_get_contents($disk_dir . '/' . $new_name);
                        $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
                        $data = $ossClient->putObject($bucket, $object, $content);
                         error_log(date('Y-m-d H:i:s')." 【阿里云oss】： ".json_encode($data)."\n\n", 3, "/tmp/". 'oss'.date('Ymd').".log");

                        $web_pic_url = $data['oss-request-url'];
                        //删除本地图片
                        // $unlink = unlink($disk_dir . '/' . $new_name);
                    } catch (\OSS\Core\OssException $e) {

                    }
                }

                //得到返回图片
                $data_return = [
                    'img_url' => $web_pic_url,
                ];

                //识别营业执照
                $is_yyzz = 1;
                if ($is_yyzz && $img_type == '1') {
                    $data_return['store_license_no'] = '';
                    $data_return['store_license_stime'] = '';
                    $data_return['store_license_time'] = '';
                    $data_return['is_long_time'] = '0';

//                    try {
                        // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
//                        $appid = env('YOUTU_appid');
//                        $secretId = env('YOUTU_secretId');
//                        $secretKey = env('YOUTU_secretKey');
//                        $userid = env('YOUTU_userid');
//                        Conf::setAppInfo($appid, $secretId, $secretKey, $userid, conf::API_YOUTU_END_POINT);
//                        $uploadRet = YouTu::bizlicenseocrurl($web_pic_url);
//                        Log::info($uploadRet);

                        date_default_timezone_set("GMT");
                        $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                        $array = array(
                            'Action' => 'RecognizeBusinessLicense',
                            'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                            'SignatureMethod' => 'HMAC-SHA1',
                            'SignatureVersion' => '1.0',
                            'SignatureNonce' => time(),
                            'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                            'Version' => '2021-07-07',
                            'Format' => 'JSON',
                            'Url' => $web_pic_url
                        );
                        $str = $this->getSignContent($array);
                        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                        $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                        $array['Signature'] = $signature;
                        $urls = $urls.http_build_query($array);
                        $result = $this->https_request1($urls);
                        $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                        $uploadRet = json_decode($result['Data'],true);
//                            dump($uploadRet);die;
                        if( isset($uploadRet['data']) ){
                            $data_return['store_license_no'] = $uploadRet['data']['creditCode']; // 营业执照编号

                            $store_license_stime = $uploadRet['data']['RegistrationDate'];
                            $store_license_stime = str_replace("年", "-", $store_license_stime);
                            $store_license_stime = str_replace("月", "-", $store_license_stime);
                            $store_license_stime = str_replace("日", "", $store_license_stime);
                            $data_return['store_license_stime'] = $store_license_stime;
//                                dump($store_license_stime);die;
                            $store_license_time = $uploadRet['data']['validPeriod'];
                            $store_license_time = str_replace("年", "-", $store_license_time);
                            $store_license_time = str_replace("月", "-", $store_license_time);
                            $store_license_time = str_replace("日", "", $store_license_time);
                            $data_return['store_license_time'] = $store_license_time;
                            if ($data_return['store_license_time'] == "/长期") {
                                $data_return['is_long_time'] = '1';
                                $data_return['store_license_time'] = substr($store_license_time,1);
                            }
                        }

//                        if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
//
//                            foreach ($uploadRet['items'] as $k => $v) {
//                                if (isset($v['item'])) {
//                                    if ($v['item'] == '注册号' || $v['item'] == "营业期限") {
//                                        if ($v['item'] == '注册号') {
//                                            //营业执照编号
//                                            $data_return['store_license_no'] = $v['itemstring'];
//                                        }
//                                        if ($v['item'] == '营业期限') {
//                                            $ex = explode('至', $v['itemstring']);
//                                            if (isset($ex[1]) && strlen($ex[1]) > 5) {
//                                                $store_license_stime = $ex[0];
//                                                $store_license_stime = str_replace("年", "-", $store_license_stime);
//                                                $store_license_stime = str_replace("月", "-", $store_license_stime);
//                                                $store_license_stime = str_replace("日", "", $store_license_stime);
//
//                                                $data_return['store_license_stime'] = $store_license_stime;
//                                                $store_license_time = $ex[1];
//                                                $store_license_time = str_replace("年", "-", $store_license_time);
//                                                $store_license_time = str_replace("月", "-", $store_license_time);
//                                                $store_license_time = str_replace("日", "", $store_license_time);
//                                                $data_return['store_license_time'] = $store_license_time;
//                                                if ($store_license_time == "长期") {
//                                                    $data_return['is_long_time'] = '1';
//                                                }
//                                            }
//                                        }
//                                    } else {
//                                        continue;
//                                    }
//                                } else {
//                                    break;
//                                }
//                            }
//
//                        }

//                    } catch (\Exception $exception) {
//
//                    }
                }

                //识别身份证正面
                $is_card_a = 1;
                if ($is_card_a && $img_type == '2') {
                    $data_return['sfz_name'] = '';
                    $data_return['sfz_no'] = '';
                    try {
//                        $array = array(
//                            'Action'=>'RecognizeIdcard',
//                            'AccessKeyId'=>'RecognizeIdcard',
//                            'SignatureMethod'=>'HMAC-SHA1',
//                            'SignatureVersion'=>'1.0',
//                            'SignatureNonce'=>time(),
//                            'Timestamp'=>date('y'),
//                            'Version'=>'2021-07-07',
//                            'Version'=>'JSON',
//                        );
//                        $accessKeyId = 'LTAI4G1WrRT1juJ1sdXN1A8e';
//                        $accessKeySecret = 'Zxhp2ANN8VQtA9SIRaA6gGe5OSdias';
//
//                        $config = new Config([
//                            // 您的AccessKey ID
//                            "accessKeyId" => $accessKeyId,
//                            // 您的AccessKey Secret
//                            "accessKeySecret" => $accessKeySecret
//                        ]);
//                        // 访问的域名
//                        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
//                        $client=new Ocrapi($config);
//                        $recognizeAdvancedRequest = new RecognizeAdvancedRequest([
//                            "url" => "https://kaifa.zgjindoufu.com/upload/images/186551888881645769661.jpg"
//                        ]);
//                        // 复制代码运行请自行打印 API 的返回值
//                        $client->recognizeAdvanced($recognizeAdvancedRequest);
//                        dump($client);die;

                        // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用

                        date_default_timezone_set("GMT");
                        $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                        $array = array(
                            'Action' => 'RecognizeIdcard',
                            'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                            'SignatureMethod' => 'HMAC-SHA1',
                            'SignatureVersion' => '1.0',
                            'SignatureNonce' => time(),
                            'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                            'Version' => '2021-07-07',
                            'Format' => 'JSON',
                            'Url' => $web_pic_url
                        );
                        $str = $this->getSignContent($array);
                        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                        $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                        $array['Signature'] = $signature;
                        $urls = $urls.http_build_query($array);
                        $result = $this->https_request1($urls);
                        $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                        $uploadRet = json_decode($result['Data'],true);
                        //                        dump($uploadRet);die;


                        //                        file_put_contents('safasasfasf.log',var_export($uploadRet,true)."\r\n",FILE_APPEND);
                        //                        if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
                        if ( isset($uploadRet['data']['face']['data']) ) {
                            if ( isset($uploadRet['data']['face']['data']['name']) ) {
                                $data_return['sfz_name'] = $uploadRet['data']['face']['data']['name']; // 身份证名字
                            }
                            if ( isset($uploadRet['data']['face']['data']['idNumber']) ) {
                                $data_return['sfz_no'] = $uploadRet['data']['face']['data']['idNumber']; // 身份证号码
                            }
                        }

//                        $appid = env('YOUTU_appid');
//                        $secretId = env('YOUTU_secretId');
//                        $secretKey = env('YOUTU_secretKey');
//                        $userid = env('YOUTU_userid');
//                        Conf::setAppInfo($appid, $secretId, $secretKey, $userid, conf::API_YOUTU_END_POINT);
//                        $uploadRet = YouTu::idcardocrurl($web_pic_url, 0);
//
//                        if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
//                            if (isset($uploadRet['name'])) {
//                                //身份证名字
//                                $data_return['sfz_name'] = $uploadRet['name'];
//                            }
//                            if (isset($uploadRet['id'])) {
//                                //身份证号码
//                                $data_return['sfz_no'] = $uploadRet['id'];
//                            }
//                        }
                    } catch (\Exception $exception) {

                    }
                }

                //识别身份证反面
                $is_card_b = 1;
                if ($is_card_b && $img_type == '3') {
                    $data_return['sfz_stime'] = '';
                    $data_return['sfz_time'] = '';
                    try {
                        // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
                        date_default_timezone_set("GMT");
                        $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                        $array = array(
                            'Action' => 'RecognizeIdcard',
                            'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                            'SignatureMethod' => 'HMAC-SHA1',
                            'SignatureVersion' => '1.0',
                            'SignatureNonce' => time(),
                            'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                            'Version' => '2021-07-07',
                            'Format' => 'JSON',
                            'Url' => $web_pic_url
                        );
                        $str = $this->getSignContent($array);
                        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                        $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                        $array['Signature'] = $signature;
                        $urls = $urls.http_build_query($array);
                        $result = $this->https_request1($urls);
                        $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                        $uploadRet = json_decode($result['Data'],true);
//                            dump($uploadRet);die; // 2018.09.30-2038.09.30
//                            dump(2);die;
                        if( isset($uploadRet['data']['back']['data']['validPeriod']) ){
//                                if (isset($uploadRet['valid_date'])) {
                            $valid_date = explode("-", $uploadRet['data']['back']['data']['validPeriod']);
//                                    dump($valid_date);die;
                            if (isset($valid_date[0])) {
                                $data_return['sfz_stime'] = $valid_date[0];
                                $data_return['sfz_stime'] = str_replace(".", "-", $data_return['sfz_stime']);
                            }
                            if (isset($valid_date[1])) {
                                $data_return['sfz_time'] = $valid_date[1];
                                $data_return['sfz_time'] = str_replace(".", "-", $data_return['sfz_time']);
                            }
//                                    dump($data_return);die;
//                                }
                        }

//                        $appid = env('YOUTU_appid');
//                        $secretId = env('YOUTU_secretId');
//                        $secretKey = env('YOUTU_secretKey');
//                        $userid = env('YOUTU_userid');
//                        Conf::setAppInfo($appid, $secretId, $secretKey, $userid, conf::API_YOUTU_END_POINT);
//                        $uploadRet = YouTu::idcardocrurl($web_pic_url, 1);
//
//                        if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
//                            if (isset($uploadRet['valid_date'])) {
//                                $valid_date = explode("-", $uploadRet['valid_date']);
//                                if (isset($valid_date[0])) {
//                                    $data_return['sfz_stime'] = $valid_date[0];
//                                    $data_return['sfz_stime'] = str_replace(".", "-", $data_return['sfz_stime']);
//                                }
//                                if (isset($valid_date[1])) {
//                                    $data_return['sfz_time'] = $valid_date[1];
//                                    $data_return['sfz_time'] = str_replace(".", "-", $data_return['sfz_time']);
//                                }
//                            }
//                        }
                    } catch (\Exception $exception) {

                    }
                }

                //识别银行卡正面
                $is_bank_a = 1;
                if ($is_bank_a && $img_type == '4') {
                    $data_return['store_bank_no'] = '';
                    $data_return['bank_name'] = '';

                    try {
                        // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
                        date_default_timezone_set("GMT");
                        $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                        $array = array(
                            'Action' => 'RecognizeBankCard',
                            'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                            'SignatureMethod' => 'HMAC-SHA1',
                            'SignatureVersion' => '1.0',
                            'SignatureNonce' => time(),
                            'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                            'Version' => '2021-07-07',
                            'Format' => 'JSON',
                            'Url' => $web_pic_url
                        );
                        $str = $this->getSignContent($array);
                        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                        $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                        $array['Signature'] = $signature;
                        $urls = $urls.http_build_query($array);
                        $result = $this->https_request1($urls);
                        $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                        $uploadRet = json_decode($result['Data'],true);
//                        dump($uploadRet);die;

                        if( isset($uploadRet['data']) ){
//                                if (isset($uploadRet['items'])) {
//                                    foreach ($uploadRet['items'] as $k => $v) {
//                                        if (isset($v['item'])) {
//                                            if ($v['item'] == '卡号') {
                            //卡号
                            $data_return['store_bank_no'] = $uploadRet['data']['cardNumber'];
//                                            }

//                                            if ($v['item'] == '卡类型') {
//                                                //卡类型
//                                                if ($v['itemstring'] == "贷记卡") {
//                                                    return json_encode([
//                                                        'status' => 2,
//                                                        'message' => '暂时不支持信用卡绑卡',
//                                                    ]);
//                                                }
//                                            }

//                                            if ($v['item'] == '银行信息') {
//                                                //卡号
//                                                $data = explode('(', $v['itemstring']);
                            $data_return['bank_name'] = $uploadRet['data']['bankName'];
//                                            }
//                                        } else {
//                                            break;
//                                        }
//                                    }
//                                }
                        }

//                        $appid = env('YOUTU_appid');
//                        $secretId = env('YOUTU_secretId');
//                        $secretKey = env('YOUTU_secretKey');
//                        $userid = env('YOUTU_userid');
//                        Conf::setAppInfo($appid, $secretId, $secretKey, $userid, conf::API_YOUTU_END_POINT);
//                        $uploadRet = YouTu::creditcardocrurl($web_pic_url, 1);
//
//                        if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
//                            if (isset($uploadRet['items'])) {
//                                foreach ($uploadRet['items'] as $k => $v) {
//                                    if (isset($v['item'])) {
//                                        if ($v['item'] == '卡号') {
//                                            //卡号
//                                            $data_return['store_bank_no'] = $v['itemstring'];
//                                        }
//                                        if ($v['item'] == '卡类型') {
//                                            //卡类型
//                                            if ($v['itemstring'] == "贷记卡") {
//                                                return json_encode([
//                                                    'status' => 2,
//                                                    'message' => '暂时不支持信用卡绑卡',
//                                                ]);
//                                            }
//                                        }
//                                        if ($v['item'] == '银行信息') {
//                                            //卡号
//                                            $data = explode('(', $v['itemstring']);
//                                            $data_return['bank_name'] = isset($data[0]) ? $data[0] : "";
//                                        }
//                                    } else {
//                                        break;
//                                    }
//                                }
//                            }
//                        }
                    } catch (\Exception $exception) {

                    }
                }

                return response()->json([
                    'status' => 1,
                    'message' => '上传成功！',
                    'data' => $data_return,
                ]);
            }

            return response()->json([
                'status' => 2,
                'message' => '上传失败！'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
            ]);
        }
    }

    //服务端上传图片
    public function webupload(Request $request){
        try {
            $action = $request->get('act'); // 获取GET参数
            $token = $request->get('token');
            $merchant = $this->parseToken($token);
//            dump($action);die;
            if ($merchant == false) {
                return response()->json([
                    'status' => 2,
                    'message' => '账户过期请重新登录！'
                ]);
            }
            $type = $request->get('type', 'store');
            $img_type = $request->get('img_type', '');
//            dump($img_type);die;
            $file_type = $request->get('file_type', 'img'); //img file

            if ($file_type == "img") {
                //上传图片具体操作
                $file_name = $_FILES['img_upload']['name'];
                $file_type = $_FILES["img_upload"]["type"];
                $file_tmp = $_FILES["img_upload"]["tmp_name"];
                $file_error = $_FILES["img_upload"]["error"];
                $file_size = $_FILES["img_upload"]["size"];
            } else {
                //上传文件具体操作
                $file_name = $_FILES['file']['name'];
                $file_type = $_FILES["file"]["type"];
                $file_tmp = $_FILES["file"]["tmp_name"];
                $file_error = $_FILES["file"]["error"];
                $file_size = $_FILES["file"]["size"];
            }
            if ($file_error > 0) { // 出错
                return json_encode([
                    'status' => 2,
                    'message' => $file_error,
                ]);
            }
            if ($file_size > 50485769999) { // 文件太大了
                return json_encode([
                    'status' => 2,
                    'message' => '上传文件过大',
                ]);
            }
            $file_name_arr = explode('.', $file_name);
            //域名授权目录提交
            $file_first = $merchant->phone.time();
            if ($type == 'wxauth') {
                $file_first = $file_name_arr[0];
            }
            $new_file_name = $file_first . '.' . $file_name_arr[1];

            if(!in_array(strtolower($file_name_arr[1]),['jpg','png','gif','jpeg','pem','mp4','key','txt'])){
                return json_encode([
                    'status' => 2,
                    'message' => '格式不支持',
                ]);
            }
            $file_path = "/upload/images/" . $new_file_name;
            if ($type == 'wxfile') {
                $file_path = "/upload/images/" . $new_file_name;
            }
            //域名授权目录提交
            if ($type == 'wxauth') {
                $file_path = "/" . $new_file_name;
            }
            if ($type == "store") {
                $file_path = "/upload/images/" . $new_file_name;
            }
            if (file_exists($file_path)) {
                return json_encode([
                    'status' => 2,
                    'message' => '文件已存在',
                ]);
            } else {
//                dump(url($file_path));die;
                $upload_result = move_uploaded_file($file_tmp, public_path() . $file_path); // 此函数只支持 HTTP POST 上传的文件

                if ($upload_result) {
                    $url = url($file_path);
                    if ($type == 'wxfile') {
                        $url = $file_path;
                    }

                    //上传到阿里云oss
                    // $oss = 0;
                    // if ($file_type == "video/mp4") {
                        $oss = 1;
                    // }
                    // Log::info($oss);
                    // Log::info(env('ALIOSS_AccessKeyId'));

                    if ($oss && env('ALIOSS_AccessKeyId')) {
                        //阿里云oss
                        $AccessKeyId = env('ALIOSS_AccessKeyId');
                        $AccessKeySecret = env('ALIOSS_AccessKeySecret');
                        $endpoint = env('ALIOSS_endpoint');
                        $bucket = env('ALIOSS_bucket');

                        $object = $new_file_name;
                        try {
                            $content = file_get_contents(public_path() . $file_path);
                            $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
                            $data = $ossClient->putObject($bucket, $object, $content);
                            Log::info('阿里云OSS结果');
                            Log::info($data);

                            $url = $data['oss-request-url'];
                            //删除本地图片
                            // $unlink = unlink(public_path() . $file_path);
                        } catch (\OSS\Core\OssException $e) {
                            Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
                        }
                    }

                    //识别营业执照
                    $is_yyzz = 1;
                    if ($is_yyzz && $img_type == '1') {
                        // print_r($url);die;
                        $data_return['store_license_no'] = '';
                        $data_return['store_license_time'] = '';
                        $data_return['store_license_stime'] = '';
                        $data_return['is_long_time'] = '0';

//                        try {
                            // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
//                            $appid = env('YOUTU_appid');
//                            $secretId = env('YOUTU_secretId');
//                            $secretKey = env('YOUTU_secretKey');
//                            $userid = env('YOUTU_userid');
//                            Conf::setAppInfo($appid, $secretId, $secretKey, $userid, conf::API_YOUTU_END_POINT);
//                            $uploadRet = YouTu::bizlicenseocrurl($url);

//                            dump($url);die;
                            date_default_timezone_set("GMT");
                            $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                            $array = array(
                                'Action' => 'RecognizeBusinessLicense',
                                'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                                'SignatureMethod' => 'HMAC-SHA1',
                                'SignatureVersion' => '1.0',
                                'SignatureNonce' => time(),
                                'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                                'Version' => '2021-07-07',
                                'Format' => 'JSON',
                                'Url' => $url
                            );
                            $str = $this->getSignContent($array);
                            $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                            $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                            $array['Signature'] = $signature;
                            $urls = $urls.http_build_query($array);
                            $result = $this->https_request1($urls);
                            $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                            // print_r($result);die;
                             error_log(date('Y-m-d H:i:s')." 【阿里云oss】： ".json_encode($result)."\n\n", 3, "/tmp/". 'oss'.date('Ymd').".log");

                            $uploadRet = json_decode($result['Data'],true);
                            
                            // dump($uploadRet);die;
                            if( isset($uploadRet['data']) ){
                                $data_return['store_license_no'] = $uploadRet['data']['creditCode']; // 营业执照编号
                                $data_return['companyName'] = $uploadRet['data']['companyName']; // 营业执照编号
                                $store_license_stime = $uploadRet['data']['RegistrationDate'];

                                $store_license_stime = str_replace("年", "-", $store_license_stime);
                                $store_license_stime = str_replace("月", "-", $store_license_stime);
                                $store_license_stime = str_replace("日", "", $store_license_stime);
                                $data_return['store_license_stime'] = $store_license_stime;
//                                dump($store_license_stime);die;
                                $store_license_time = $uploadRet['data']['validPeriod'];
                                $store_license_time = str_replace("年", "-", $store_license_time);
                                $store_license_time = str_replace("月", "-", $store_license_time);
                                $store_license_time = str_replace("日", "", $store_license_time);
                                $data_return['store_license_time'] = $store_license_time;
                                if ($data_return['store_license_time'] == "/长期") {
                                    // $data_return['is_long_time'] = '1';
                                    $data_return['store_license_time'] = '2099-12-01';
                                }
                            }
//                            dump($data_return);die;
                    }

                    //识别身份证正面
                    $is_card_a = 1;
                    if ($is_card_a && $img_type == '2') {
                        $data_return['sfz_name'] = '';
                        $data_return['sfz_no'] = '';
                        try {
                            // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
                            date_default_timezone_set("GMT");
                            $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                            $array = array(
                                'Action' => 'RecognizeIdcard',
                                'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                                'SignatureMethod' => 'HMAC-SHA1',
                                'SignatureVersion' => '1.0',
                                'SignatureNonce' => time(),
                                'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                                'Version' => '2021-07-07',
                                'Format' => 'JSON',
                                'Url' => $url
                            );
                            $str = $this->getSignContent($array);
                            $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                            $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                            $array['Signature'] = $signature;
                            $urls = $urls.http_build_query($array);
                            $result = $this->https_request1($urls);
                            $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                            $uploadRet = json_decode($result['Data'],true);
    //                        dump($uploadRet);die;


    //                        file_put_contents('safasasfasf.log',var_export($uploadRet,true)."\r\n",FILE_APPEND);
    //                        if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
                            if ( isset($uploadRet['data']['face']['data']) ) {
                                if ( isset($uploadRet['data']['face']['data']['name']) ) {
                                    $data_return['sfz_name'] = $uploadRet['data']['face']['data']['name']; // 身份证名字
                                }
                                if ( isset($uploadRet['data']['face']['data']['idNumber']) ) {
                                    $data_return['sfz_no'] = $uploadRet['data']['face']['data']['idNumber']; // 身份证号码
                                }
                            }
                        } catch (\Exception $exception) {

                        }
                    }

                    //识别身份证反面
                    $is_card_b = 1;
                    if ($is_card_b && $img_type == '3') {
                        $data_return['sfz_time'] = '';
                        $data_return['sfz_stime'] = '';

                        try {
                            // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
//                            $appid = env('YOUTU_appid');
//                            $secretId = env('YOUTU_secretId');
//                            $secretKey = env('YOUTU_secretKey');
//                            $userid = env('YOUTU_userid');
//                            Conf::setAppInfo($appid, $secretId, $secretKey, $userid, conf::API_YOUTU_END_POINT);
//                            $uploadRet = YouTu::idcardocrurl($url, 1);

                            date_default_timezone_set("GMT");
                            $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                            $array = array(
                                'Action' => 'RecognizeIdcard',
                                'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                                'SignatureMethod' => 'HMAC-SHA1',
                                'SignatureVersion' => '1.0',
                                'SignatureNonce' => time(),
                                'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                                'Version' => '2021-07-07',
                                'Format' => 'JSON',
                                'Url' => $url
                            );
                            $str = $this->getSignContent($array);
                            $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                            $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                            $array['Signature'] = $signature;
                            $urls = $urls.http_build_query($array);
                            $result = $this->https_request1($urls);
                            $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                            $uploadRet = json_decode($result['Data'],true);
//                            dump($uploadRet);die; // 2018.09.30-2038.09.30
//                            dump(2);die;
                            if( isset($uploadRet['data']['back']['data']['validPeriod']) ){
//                                if (isset($uploadRet['valid_date'])) {
                                    $valid_date = explode("-", $uploadRet['data']['back']['data']['validPeriod']);
//                                    dump($valid_date);die;
                                    if (isset($valid_date[0])) {
                                        $data_return['sfz_stime'] = $valid_date[0];
                                        $data_return['sfz_stime'] = str_replace(".", "-", $data_return['sfz_stime']);
                                    }
                                    if (isset($valid_date[1])) {
                                        $data_return['sfz_time'] = $valid_date[1];
                                        $data_return['sfz_time'] = str_replace(".", "-", $data_return['sfz_time']);
                                    }
//                                    dump($data_return);die;
//                                }
                            }

//                            if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
//                                if (isset($uploadRet['valid_date'])) {
//                                    $valid_date = explode("-", $uploadRet['valid_date']);
//                                    if (isset($valid_date[0])) {
//                                        $data_return['sfz_stime'] = $valid_date[0];
//                                        $data_return['sfz_stime'] = str_replace(".", "-", $data_return['sfz_stime']);
//                                    }
//                                    if (isset($valid_date[1])) {
//                                        $data_return['sfz_time'] = $valid_date[1];
//                                        $data_return['sfz_time'] = str_replace(".", "-", $data_return['sfz_time']);
//                                    }
//                                }
//                            }
                        } catch (\Exception $exception) {

                        }
                    }

                    //识别银行卡正面
                    $is_bank_a = 1;
                    if ($is_bank_a && $img_type == '4') {
                        $data_return['store_bank_no'] = '';
                        $data_return['bank_name'] = '';

                        try {
                            // 设置APP 鉴权信息 请在http://open.youtu.qq.com 创建应用
//                            $appid = env('YOUTU_appid');
//                            $secretId = env('YOUTU_secretId');
//                            $secretKey = env('YOUTU_secretKey');
//                            $userid = env('YOUTU_userid');
//                            Conf::setAppInfo($appid, $secretId, $secretKey, $userid, conf::API_YOUTU_END_POINT);
//                            $uploadRet = YouTu::creditcardocrurl($url, 1);

                            date_default_timezone_set("GMT");
                            $urls = 'https://ocr-api.cn-hangzhou.aliyuncs.com/?';
                            $array = array(
                                'Action' => 'RecognizeBankCard',
                                'AccessKeyId' => 'LTAI5tAVMkT5c9gHpQM9BaVA',
                                'SignatureMethod' => 'HMAC-SHA1',
                                'SignatureVersion' => '1.0',
                                'SignatureNonce' => time(),
                                'Timestamp' => date('Y-m-d\TH:i:s\Z',time()),
                                'Version' => '2021-07-07',
                                'Format' => 'JSON',
                                'Url' => $url
                            );
                            $str = $this->getSignContent($array);
                            $stringToSign = 'GET&%2F&' . $this->percentencode(substr($str, 0)); // 生成用于计算签名的字符串 stringToSign
                            $signature = base64_encode(hash_hmac('sha1', $stringToSign, '7m0DcCcfYpJkobEeGvnwDur27qswVr' . '&', true));
                            $array['Signature'] = $signature;
                            $urls = $urls.http_build_query($array);
                            $result = $this->https_request1($urls);
                            $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
                            $uploadRet = json_decode($result['Data'],true);
//                            dump($uploadRet);die;

                            if( isset($uploadRet['data']) ){
//                                if (isset($uploadRet['items'])) {
//                                    foreach ($uploadRet['items'] as $k => $v) {
//                                        if (isset($v['item'])) {
//                                            if ($v['item'] == '卡号') {
                                                //卡号
                                                $data_return['store_bank_no'] = $uploadRet['data']['cardNumber'];
//                                            }

//                                            if ($v['item'] == '卡类型') {
//                                                //卡类型
//                                                if ($v['itemstring'] == "贷记卡") {
//                                                    return json_encode([
//                                                        'status' => 2,
//                                                        'message' => '暂时不支持信用卡绑卡',
//                                                    ]);
//                                                }
//                                            }

//                                            if ($v['item'] == '银行信息') {
//                                                //卡号
//                                                $data = explode('(', $v['itemstring']);
                                                $data_return['bank_name'] = $uploadRet['data']['bankName'];
//                                            }
//                                        } else {
//                                            break;
//                                        }
//                                    }
//                                }
                            }

//                            if (isset($uploadRet['errorcode']) && $uploadRet['errorcode'] == 0) {
//                                if (isset($uploadRet['items'])) {
//                                    foreach ($uploadRet['items'] as $k => $v) {
//                                        if (isset($v['item'])) {
//                                            if ($v['item'] == '卡号') {
//                                                //卡号
//                                                $data_return['store_bank_no'] = $v['itemstring'];
//                                            }
//
//                                            if ($v['item'] == '卡类型') {
//                                                //卡类型
//                                                if ($v['itemstring'] == "贷记卡") {
//                                                    return json_encode([
//                                                        'status' => 2,
//                                                        'message' => '暂时不支持信用卡绑卡',
//                                                    ]);
//                                                }
//                                            }
//
//                                            if ($v['item'] == '银行信息') {
//                                                //卡号
//                                                $data = explode('(', $v['itemstring']);
//                                                $data_return['bank_name'] = isset($data[0]) ? $data[0] : "";
//                                            }
//                                        } else {
//                                            break;
//                                        }
//                                    }
//                                }
//                            }
                        } catch (\Exception $exception) {

                        }
                    }

                    $data_return['img_url'] = $url;
//                    echo '<pre>';
//                    print_r($data_return);
//                    die;
                    return json_encode([
                        'status' => 1,
                        'data' => $data_return,
                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => '系统错误重新上传',
                    ]);
                }
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getLine(),
            ]);
        }
    }

    //参数拼接
    public function getSignContent($params){
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;

        foreach ($params as $k => $v) {

            //空值和数组,不参与签名组串
            if (is_array($v) || true === $this->checkEmpty($v)) {
//                dump($v);die;
                continue;
            }
//            dump($v);die;
            $v = $this->characet($v, "UTF-8"); // 转换成目标字符集
            if ($i == 0) {
                $stringToBeSigned .= "$k" . "=" . "$v";
            } else {
                $stringToBeSigned .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }

    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value)
    {
        $value = trim($value);

        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if ($value === "")
            return true;
        if ($value === [])
            return true;
        if (empty($value))
            return true;

        return false;
    }

    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = "UTF-8";
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
//				$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }

    public function percentEncode($str){
        $res = preg_replace('/&/', '%26', $str);
        $res = preg_replace('/=/', '%3D', $res);
        $res = preg_replace('/:/', '%253A', $res);
        $res = preg_replace('/\//', '%252F', $res);
        return $res;
    }

    public function https_request1($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    public function file_content(Request $request)
    {
        try {
            $token = $request->get('token');
            $this->parseToken($token);
            $store_id = $request->get('store_id');
            $merchant_id = $request->get('merchant_id');
            $http_curl = $request->get('http_curl', '');
            $content = $request->get('content', '');
            $gs = $request->get('gs', '.mp3');
            $type = $request->get('type', $store_id);
            $price = $request->get('price', $merchant_id . rand(1, 100));

            if ($http_curl) {
                $obj = new \App\Api\Controllers\Suzhou\BaseController();
                $content = $obj->http_curl($http_curl, json_encode(''));
            }

            $file = '/upload/' . $type . $price . $gs;
            $file1 = public_path() . $file;

            if (!file_exists($file1)) {
                $fp = fopen($file1, 'w');
                fwrite($fp, $content);
                fclose($fp);
            }

            $url = url($file);

            return json_encode([
                'status' => 1,
                'message' => '返回成功',
                'data' => [
                    'url' => $url
                ]
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }
    }


}
